<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="门店" prop="shopId">
        <el-select
          v-model="form.shopId"
          placeholder="请选择门店"
          clearable
          @change="updateScId(form.shopId)"
          :style="{width: '100%'}">
          <el-option
            v-for="(item, index) in shopList"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerName">
        <el-select v-model="form.customerId" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in customer" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售员" prop="salerName" v-if="this.$store.state.user.name == 'admin'">
        <el-select v-model="form.salerId" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" v-if="this.$route.query.id">
        <div>
          <span>{{ form.status == 0 ? '未审核' : form.status == 3 ? '审核通过' : '审核拒绝'}}</span>
        </div>
      </el-form-item><br>
      <el-form-item label="操作人" prop="createBy" v-if="this.$route.query.id">
        <div>
          <span>{{ form.createBy }}</span>
        </div>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime" v-if="this.$route.query.id">
        <div>
          <span>{{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </div>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-left: 20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tblSaleOrderDetailList" @selection-change="handleSelectionChange" height="500" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" prop="baseDataProduct.code" align="center" width="100" show-overflow-tooltip/>
      <el-table-column label="商品名称" prop="baseDataProduct.name" align="center" width="200">
        <template slot-scope="scope">
          <el-autocomplete
            class="inline-input"
            v-model="scope.row.baseDataProduct.name"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect(scope.row,$event)"
          >
          <template slot-scope="{ item }">
            <span>{{ item.name }}</span>
          </template>
        </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column label="单位" prop="baseDataProduct.unit" align="center" />
      <el-table-column label="规格" prop="baseDataProduct.spec" align="center" />
      <el-table-column label="商品类目" prop="baseDataProduct.baseDataProductCategory.name" align="center" />
      <el-table-column label="商品品牌" prop="baseDataProduct.baseDataProductBrand.name" align="center" />
      <el-table-column label="参考销售价（元）" prop="oriPrice" align="center" width="130"/>
      <el-table-column label="库存数量" prop="baseDataProduct.tblProductStock.stockNum" align="center" />
      <el-table-column label="折扣（%）" prop="discountRate" align="center" width="100">
        <template slot-scope="scope">
          <el-input v-model="scope.row.discountRate" @input="getTaxPrice(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="价格（元）" prop="taxPrice" align="center" width="100">
        <template slot-scope="scope">
          <el-input v-model="scope.row.taxPrice" @input="getDiscountRate(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="销售数量" prop="orderNum" align="center" >
        <template slot-scope="scope">
          <el-input v-model="scope.row.orderNum" @input="getAmount()"/>
        </template>
      </el-table-column>
      <el-table-column label="金额（元）" prop="amount" align="center" width="100">
        <template slot-scope="scope" v-if="scope.row.orderNum">
          <span>{{ Number((scope.row.taxPrice * scope.row.orderNum) - scope.row.taxPrice * scope.row.orderNum * (parseInt(scope.row.baseDataProduct.baseDataProductCategory.saleTaxRate) / 100)).toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="含税金额" prop="taxAmount" align="center" >
        <template slot-scope="scope" v-if="scope.row.orderNum">
          <span>{{ Number(scope.row.taxPrice * scope.row.orderNum).toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="税率（%）" prop="baseDataProduct.baseDataProductCategory.saleTaxRate" align="center" width="100"/>
      <el-table-column label="备注" prop="description" align="center" >
        <template slot-scope="scope">
          <el-input v-model="scope.row.description" />
        </template>
      </el-table-column>
    </el-table>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
      <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
      <div style="display: inline-block;margin-left:50px">
        销售数量：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.form.totalNum">
      </div>
      <div style="display: inline-block;margin-left:50px">
        含税总金额：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="Number(this.form.totalAmount).toLocaleString()">
      </div>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
      <h3 style="margin:0 0 15px 10px;font-weight: bolder;margin-left: 10px">约定支付</h3>
      <el-row :gutter="10" class="mb8" style="margin-left: 20px">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="payAdd"
            v-hasPermi="['system:product:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="payDelete"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-table :data="OrderPayTypeList" height="300px" @selection-change="paySelectionChange"  ref="tblPurchaseOrderDetail">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="支付方式" prop="payTypeId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.payTypeId" clearable @change="handlePayTypeChange(scope.row)">
                <el-option v-for="(user,index) in OrderPayType" :key="index" :value="user.id" :label="user.name"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="支付金额" prop="payAmount" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.payAmount" placeholder="请输入支付金额" />
            </template>
          </el-table-column>
          <el-table-column label="支付记录" prop="text" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.text" placeholder="" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
      <label >备注： </label>
      <textarea style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="this.form.description"/>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {customer, center, getOrder, addOrder,listOrder, updateOrder } from "@/api/system/order";
import { listUser } from "@/api/system/user";
import {parseTime} from "../../../utils/ruoyi";
import {listPayType}from "@/api/system/PayType";
import {listStock} from "@/api/system/stock";
import {getShop, listShop} from "../../../api/system/Shop";

export default {
  name: "orderAdd",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      payTypes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单商品数据列表
      tblSaleOrderDetailList: [],
      // 商品框
      restaurants: [],
      // 销售数量
      orderNum: null,
      // 赠品数量
      giftNum: null,
      // 含税总金额
      taxAmount: null,
      // 仓库下拉框
      ck: [],
      // 用户(审核人、操作人、销售员)下拉框
      user: [],
      // 客户下拉框
      customer: [],
      // 订单支付方式
      OrderPayTypeList: [],
      // 支付下拉框
      OrderPayType: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        id: 0,
        code: '',
        name: '',
        scId: '',
        scName: '',
        customerId: '',
        customerName: '',
        salerId: '',
        salerName: '',
        skuCode: '',
        externalCode: '',
        unit: '',
        spec: '',
        categoryId: '',
        categoryName: '',
        brandId: '',
        brandName: '',
        price: '',
        isGift: 0,
        stockNum: '',
        discountRate: 100,
        taxPrice: '',
        orderNum: '',
        taxAmount: '',
        taxRate: 10,
        description: '',
        tblSaleOrderDetailList: [],
        OrderPayTypeList: [],
      },
      // 根据订单ID查询订单支付方式
      payType: {
        orderId: null,
      },
      // 表单校验
      rules: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
      },
      //订单表ID数据
      OrderAllList:[],
      //订单详情表ID数据
      OrderDetailAllList:[],
      //订单支付ID数据
      orderPayTypeAllList:[],
      //商品库存id
      productStockAllList:[],

      shopList: [], // 门店列表
    };
  },
  created() {
    this.getList();
    this.gettblSaleOrderDetailList();
  },
  methods: {
    parseTime,
    /** 查询订单详情 */
    getList() {
      this.loading = true;
      customer(this.customer).then(response => {
        this.customer = response.rows;
      });
      center(this.ck).then(response => {
        this.ck = response.rows;
      });
      listUser(this.user).then(response => {
        this.user = response.rows;
      });
      listPayType().then(response => {
        this.OrderPayType = response.rows;
      });
      this.OrderDetailAllList=[];
      listOrder({}).then(response => {
        this.OrderDetailAllList = response.rows;
        let list=response.rows;
        for (var i=0;i<list.length;i++){
          this.OrderAllList.push(list[i].id);
        }
      });
      listShop().then(response => {
        this.shopList = response.rows;
      });
      if (this.$route.query.id && this.tblSaleOrderDetailList != null){
        getOrder(this.$route.query.id).then(response => {
          this.form = response.data;
          this.tblSaleOrderDetailList = response.data.tblSaleOrderDetailList;

          this.OrderPayTypeList = response.data.tblOrderPayTypeList;
          //根据仓库id和订单中的商品id，循环获取订单商品详情的库存数量
          for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
            this.selectProductStockList(this.form.scId, this.tblSaleOrderDetailList[i])
          }
          this.gettblSaleOrderDetailList(this.form.scId);
          console.log(this.form);
        });
      }
      this.loading = false;
    },
    //获取库存列表
    selectProductStockList(scId, tblSaleOutSheetDetail) {
      listStock({scId,productId:tblSaleOutSheetDetail.productId}).then(response => {
        // this.productStock = response.rows[0];
        if (response.rows.length === 0){
          tblSaleOutSheetDetail.baseDataProduct.tblProductStock = {
            id: generateUniqueId(this.productStockAllList),
            productId: tblSaleOutSheetDetail.productId,
            scId: scId,
            stockNum: 0,
            taxPrice: tblSaleOutSheetDetail.taxPrice,
            taxAmount: 0,
          }
        }
        tblSaleOutSheetDetail.baseDataProduct.tblProductStock = response.rows[0];
      });
    },
    getDiscountRate(row){
      if (row.taxPrice && row.oriPrice) {
        row.discountRate = ((row.taxPrice / row.oriPrice) * 100).toFixed(2);
        this.getAmount();
      }
    },
    getTaxPrice(row){
      if (row.oriPrice) {
        row.taxPrice = row.oriPrice * (row.discountRate / 100).toFixed(2);
        this.getAmount();
      }
    },
    getAmount(){
      this.getOrderNum();
      this.getGiftNum();
      this.getTaxAmount();
    },
    // 取消按钮
    cancel() {
      // 关闭当前页面并跳转到指定页面
      this.$store.dispatch("tagsView/delView", this.$route); // 关闭当前页
      this.$router.back();
    },
    // 循环遍历，获取销售总数量
    getOrderNum() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
        sum += parseInt(this.tblSaleOrderDetailList[i].orderNum);
      }
      this.$set(this.form, 'totalNum', sum);
    },
    // 循环遍历，获取赠品总数量
    getGiftNum() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
        if (this.tblSaleOrderDetailList[i].isGift == 1){
          sum += this.tblSaleOrderDetailList[i].orderNum;
        }
      }
      this.$set(this.form, 'totalGiftNum', sum);
    },
    // 循环遍历，获取含税总金额
    getTaxAmount() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
        sum += this.tblSaleOrderDetailList[i].taxPrice * this.tblSaleOrderDetailList[i].orderNum;
      }
      this.taxAmount = sum;
      this.$set(this.form, 'totalAmount', sum);
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    paySelectionChange(selection){
      this.payTypes = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 商品新增按钮操作 */
    handleAdd() {
      if (this.form.shopId == null || this.form.shopId === ''){
        this.$modal.msgError("请先选择门店");
        return;
      }
      const id = generateUniqueId(this.OrderDetailAllList);
      // 添加一个新的空商品对象到商品列表中
      this.tblSaleOrderDetailList.push({
        baseDataProduct: {
          name: '',
          id: null,
          code: null,
          skuCode: null,
          externalCode: null,
          unit: null,
          spec: null,
          baseDataProductCategory: {
            name: '',
            saleTaxRate: 10,
          },
          baseDataProductBrand: { name: '' },
          tblProductStock:{ stockNum: 0}
        },
        id: id,
        code: null,
        name: null,
        oriPrice: null,
        isGift: 0,
        discountRate: 100,
        taxPrice: null,
        orderNum: null,
        orderNo: this.tblSaleOrderDetailList.length + 1,
        taxAmount: null,
        description: null
      });
    },
    // 约定支付新增
    payAdd(){
      if (this.form.shopId == null || this.form.shopId === ''){
        this.$modal.msgError("请先选择门店");
        return;
      }
      const newId = generateUniqueId(this.orderPayTypeAllList);
      this.orderPayTypeAllList.push(newId);
      if (this.OrderPayTypeList.length===0){
        this.OrderPayTypeList.push({
          id:newId,
          orderId:this.$route.query.id,
          payTypeId:null,
          payAmount:this.taxAmount,
          text:null
        })
      }else{
        let sum=this.form.totalAmount;
        for (let i = 0; i < this.OrderPayTypeList.length; i++) {
          sum-=this.OrderPayTypeList[i].payAmount;
        }
        if (sum < 0){
          this.$modal.msgError("支付金额已超出，请检查");
          return;
        }
        this.OrderPayTypeList.push({
          id:newId,
          orderId:this.$route.query.id,
          payTypeId:null,
          payAmount:sum,
          text:null
        })
      }
    },

    /** 提交按钮 */
    submitForm() {
      if(this.formInfo()) {
        if (this.$route.query.id) {
          for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
            this.tblSaleOrderDetailList[i].taxRate=this.tblSaleOrderDetailList[i].baseDataProduct.baseDataProductCategory.saleTaxRate;
          }
          this.form.tblOrderPayTypeList=this.OrderPayTypeList;
          this.form.tblSaleOrderDetailList=this.tblSaleOrderDetailList;
          console.log(this.form)
          updateOrder(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }else{
          const newId = generateUniqueId(this.OrderAllList);
          var orderCode = getOrderCode(this.OrderDetailAllList);
          this.form.id=newId;
          this.form.code=orderCode;
          for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
            this.tblSaleOrderDetailList[i].orderId=newId;
            this.tblSaleOrderDetailList[i].taxRate=this.tblSaleOrderDetailList[i].baseDataProduct.baseDataProductCategory.saleTaxRate;
          }
          for (let i = 0; i < this.OrderPayTypeList.length; i++) {
            this.OrderPayTypeList[i].orderId=newId;
          }
          this.form.tblOrderPayTypeList=this.OrderPayTypeList;
          this.form.tblSaleOrderDetailList=this.tblSaleOrderDetailList;
          this.form.createBy="系统管理员";
          this.form.createById="1";
          this.form.updateBy="系统管理员";
          this.form.updateById="1";
          this.form.status=0;

          console.log(this.form);
          addOrder(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },
    beforeRouteLeave(to, from, next) {
      // 设置一个标志，表示需要刷新数据
      to.meta.xsdd = true;
      next();
    },
    //提交表单验证
    formInfo(){
      if (this.form.shopId==null || this.form.shopId===''){
        this.$modal.msgError("请选择门店");
        return false;
      }else if (this.form.customerId==null || this.form.customerId===''){
        this.$modal.msgError("请选择客户");
        return false;
      }

      if (this.$store.state.user.name == 'admin'){
        if (this.form.salerId==null || this.form.salerId===''){
          this.$modal.msgError("请选择销售员");
          return false;
        }
      }

      //订单详情验证
      for (var i=0;i<this.tblSaleOrderDetailList.length;i++){
        if (this.tblSaleOrderDetailList[i].id==null){
          this.$modal.msgError("请选择商品");
          return false;
        }else if (this.tblSaleOrderDetailList[i].orderNum==null){
          this.$modal.msgError("请输入数量");
          return false;
        }
      }

      //支付方式验证
      var sum=0;
      for (var j=0;j<this.OrderPayTypeList.length;j++){
        sum+=Number(this.OrderPayTypeList[j].payAmount);
        if (this.OrderPayTypeList[j].payTypeId==null){
          this.$modal.msgError("请选择支付方式");
          return false;
        }
      }

      if(sum!=this.form.totalAmount){
        this.$modal.msgError("支付金额与订单金额不相等");
        return false;
      }
      return true;
    },
    // 商品列表
    gettblSaleOrderDetailList(scId) {
      listStock({scId}).then(response => {
        this.restaurants = response.rows.map(item => ({
          value: item.productId,  // 使用商品 ID 作为 value
          name: item.productName,
          code: item.productCode,
          skuCode: item.skuCode,
          externalCode: item.externalCode,
          unit: item.unit,
          spec: item.spec,
          ProductCategory: item.productType,
          ProductBrand: item.productBrand,
          oriPrice: item.oriPrice,
          isGift: item.isGift,
          taxPrice: item.taxPrice,
          orderNum: item.orderNum,
          taxAmount: item.taxAmount,
          stockNum: item.stockNum,
          taxRate: item.taxRate,
          saleTaxRate: item.saleTaxRate,
          description: item.description
        }));
      });
    },
    updateScId(shopId){
      let scId = null;
      if (shopId!=null && shopId!==''){
        getShop(shopId).then(response => {
          scId = response.data.scId;
          if (scId!=null && this.tblSaleOrderDetailList.length>0) {
            this.$modal.confirm('修改门店将清空商品列表，是否确认修改？').then(() => {
              this.tblSaleOrderDetailList = []; // 清空商品列表
              this.OrderPayTypeList = [];  //清空约定支付列表
              this.gettblSaleOrderDetailList(scId);
              this.getAmount();
            }).catch(() => {
            });
          }else{
            this.gettblSaleOrderDetailList(scId);
          }
        });
      }
    },
    // 约定支付方式下拉选中
    handlePayTypeChange(item){
      const list = [...this.OrderPayTypeList]; // 克隆数组避免污染原始数据
      let count = 0;

      for (const row of list) {
        if (row.payTypeId === item.payTypeId && row.id !== item.id) {
          count++;
        }
      }

      if (count >= 1) {
        this.$modal.msgError("该支付方式已存在！");
        item.payTypeId = null;
        this.$set(this.OrderPayTypeList, this.OrderPayTypeList.indexOf(item), item); // 强制更新响应式数据
      }
    },
    // 商品下拉选中
    handleSelect(row, item) {
      for (let i = 0; i < this.tblSaleOrderDetailList.length; i++) {
        if (this.tblSaleOrderDetailList[i].baseDataProduct.name === item.name){
          this.$modal.msgError("商品已存在");
          this.tblSaleOrderDetailList[this.tblSaleOrderDetailList.length-1].baseDataProduct = {
            name: '',
            id: null,
            code: null,
            skuCode: null,
            externalCode: null,
            unit: null,
            spec: null,
            baseDataProductCategory: {
              name: '',
              saleTaxRate: 10,
            },
            baseDataProductBrand: { name: '' },
            tblProductStock:{ stockNum: 0}
          };
          return;
        }
      }
      // 将选中的商品名称赋值给当前行的商品名称
      row.baseDataProduct.name = item.name;
      // 将选中的商品 ID 赋值给当前行的商品 ID
      row.baseDataProduct.id = item.value;
      row.productId=item.value;
      // 将选中的商品 Code 编号赋值给当前行的商品 Code 编号
      row.baseDataProduct.code = item.code;
      // 将选中的商品 SKU 编号赋值给当前行的商品 SKU 编号
      row.baseDataProduct.skuCode = item.skuCode;
      // 将选中的商品外部编号赋值给当前行的商品外部编号
      row.baseDataProduct.externalCode = item.externalCode;
      // 将选中的商品单位赋值给当前行的商品单位
      row.baseDataProduct.unit = item.unit;
      // 将选中的商品规格赋值给当前行的商品规格
      row.baseDataProduct.spec = item.spec;
      // 将选中的商品类目赋值给当前行的商品类目
      row.baseDataProduct.baseDataProductCategory.name = item.ProductCategory;
      // 商品销售税率
      row.baseDataProduct.baseDataProductCategory.saleTaxRate = item.saleTaxRate;
      // 将选中的商品品牌赋值给当前行的商品品牌
      row.baseDataProduct.baseDataProductBrand.name = item.ProductBrand;
      // 库存数量
      row.baseDataProduct.tblProductStock.stockNum = item.stockNum;
      // 销售价格
      row.oriPrice=item.taxPrice;
      row.taxPrice=item.taxPrice;
      //备注
      row.description=item.description;

      // 重新计算金额
      this.getAmount();

      console.log(item)
    },
    // 商品框
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.code ? [row.code] : this.ids;
      this.$modal.confirm('是否确认删除该商品列表？').then(() => {
        this.tblSaleOrderDetailList = this.tblSaleOrderDetailList.filter(product => !ids.includes(product.id));
        this.handleSelectionChange([]); // 清空选中项
        this.getAmount();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 约定支付删除
    payDelete(row){
      const payTypes = row.id ? [row.id] : this.payTypes;
      console.log(payTypes);
      this.$modal.confirm('是否确认删除选中的约定支付？').then(() => {
        this.OrderPayTypeList = this.OrderPayTypeList.filter(payType => !payTypes.includes(payType.id));
        this.paySelectionChange([]); // 清空选中项
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/SettleInItem/export', {
        ...this.queryParams
      }, `SettleInItem_${new Date().getTime()}.xlsx`)
    },
  }
};
// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="XSDD";
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
